<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { toNumber } from 'lodash-es'
import qs from 'qs'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/drawactprize'
import { GetAllData } from '@/api/modules/merchandiseControl'
import { GetOptionData } from '@/api/modules/voucher'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  prizeName: '',
  prizePic: '',
  prizePicScreen: '',
  prizeType: 1,
  productId: 0,
  change: 0,
  prizeNums: 0,
  usedNums: 0,
  flag: -1,
  ticketId: 0,
  sort: 0,
  drawId: 0,
})

const prizeTypeOption = [
  {
    label: '券',
    value: 1,
  },
  // {
  //   label: '实物',
  //   value: 2,
  // },
  // {
  //   label: '红包',
  //   value: 3,
  // },
]
interface ProductOptionType {
  productName: string
  productId: number
  cdnProductPhotoPic: string
}
interface CouponOptionType {
  name: string
  id: number
}
interface OptionListType {
  ProductOption: ProductOptionType[]
  CouponOption: CouponOptionType[]
}
const OptionList = ref<OptionListType>(
  {
    ProductOption: [],
    CouponOption: [],
  },
)

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  if (url) {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData() {
  const params = ruleForm.value
  if (id) {
    // 编辑
    params.prizeId = toNumber(id)
    params.change = toNumber(params.change)
    params.drawId = toNumber(params.drawId)
    params.prizeNums = toNumber(params.prizeNums)
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'drawactprizeIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`编辑失败。${errorStr}`)
        }
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyDrawactprize()
        router.push({ name: 'drawactprizeIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`添加失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`添加失败。${errorStr}`)
        }
      }
    })
  }
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberDrawactprize(newValue)
  }
}, { deep: true })

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.GetDrawactprizeData()
  }
  const params = qs.stringify({ ProductName: '', IsActive: true })
  const productData: any = await GetAllData(params)
  const couponData: any = await GetOptionData()
  if (productData.succeeded && couponData.succeeded) {
    OptionList.value.ProductOption = productData.data
    OptionList.value.CouponOption = couponData.data
    nextTick(() => {
      OptionList.value.ProductOption = productData.data
      OptionList.value.CouponOption = couponData.data
    })
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="奖品名称">
              <el-input v-model="ruleForm.prizeName" style="width: 300px;" placeholder="请输入奖品名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="排序">
              <el-input v-model="ruleForm.sort" style="width: 300px;" placeholder="请输入排序" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="中奖概率">
              <el-input v-model="ruleForm.change" type="number" style="width: 300px;" placeholder="请输入中奖概率" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="是否启用">
              <el-switch
                v-model="ruleForm.flag"
                :active-value="1"
                :inactive-value="-1"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.prizePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'prizePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="广告机奖品图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.prizePicScreen" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'prizePicScreen')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品库存">
              <el-input v-model="ruleForm.prizeNums" type="number" style="width: 300px;" placeholder="请输入奖品库存" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="已消耗库存">
              <el-input v-model="ruleForm.usedNums" type="number" style="width: 300px;" placeholder="请输入已消耗库存" />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="预留字段">
              <el-input v-model="ruleForm.sort" type="number" style="width: 300px;" placeholder="请输入已消耗库存" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="活动ID">
              <el-input v-model="ruleForm.drawId" type="number" style="width: 300px;" placeholder="请输入活动ID" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖品类型">
              <el-select v-model="ruleForm.prizeType" placeholder="请选择奖品类型" style="width: 300px;">
                <el-option
                  v-for="items in prizeTypeOption" :key="items.value" :label="items.label" :value="items.value"
                />
              </el-select>
            </elformitem>
          </ElCol>
          <ElCol v-if="ruleForm.prizeType === 2" :md="8">
            <ElFormItem label="实物商品">
              <el-select v-model="ruleForm.productId" placeholder="请选择实物商品" style="width: 300px;">
                <el-option
                  v-for="items in OptionList.ProductOption" :key="items.productId" :label="items.productName" :value="items.productId"
                />
              </el-select>
            </elformitem>
          </ElCol>
          <ElCol v-if="ruleForm.prizeType === 1" :md="8">
            <ElFormItem label="券">
              <el-select v-model="ruleForm.ticketId" placeholder="请选择券" style="width: 300px;">
                <el-option
                  v-for="items in OptionList.CouponOption" :key="items.id" :label="items.name" :value="items.id"
                />
              </el-select>
            </elformitem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="活动开始时间">
              <el-date-picker
                v-model="ruleForm.beginTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="请选择活动开始的日期时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动结束时间">
              <el-date-picker
                v-model="ruleForm.endTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="请选择活动结束的日期时间"
              />
            </ElFormItem>
          </ElCol> -->
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
